<!DOCTYPE html>
<html>

<head>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">


    <title>H+ 后台主题UI框架 - Bootstrap Table</title>
    <meta name="keywords" content="H+后台主题,后台bootstrap框架,会员中心主题,后台HTML,响应式后台">
    <meta name="description" content="H+是一个完全响应式，基于Bootstrap3最新版本开发的扁平化主题，她采用了主流的左右两栏式布局，使用了Html5+CSS3等现代技术">

    <link rel="shortcut icon" href="favicon.ico"> 
    <link href="../../css/bootstrap.min.css?v=3.3.6" rel="stylesheet">
    <link href="../../css/font-awesome.css?v=4.4.0" rel="stylesheet">
    <link href="../../css/plugins/bootstrap-table/bootstrap-table.min.css" rel="stylesheet">
    <link href="../../css/animate.css" rel="stylesheet">
    <link href="../../css/plugins/ztree/style.css?v=4.1.0" rel="stylesheet">

</head>
<style type="text/css">
    .setOs{
        width: 20%;
        height: 26px;
    }
</style>
<body class="">
    <div class="wrapper wrapper-content animated fadeInRight">
        <div id="toolbar" class="ibox toolbar margin">
                <div class="form-inline">
                    <div class="form-group">
                        <label for="account">登录名</label>
                        <input type="text" class="form-control" data-bind="value:account"  id="account" placeholder="Jane Doe">
                    </div>
                    <button id="btn_search" type="button" class="btn btn-default">
                        搜索
                    </button> 
                    <button id="btn_add" type="button" class="btn btn-default">
                        <span class="glyphicon glyphicon-plus" aria-hidden="true"></span>新增
                    </button>
                    <button id="btn_edit" type="button" class="btn btn-default">
                        <span class="glyphicon glyphicon-pencil" aria-hidden="true"></span>修改
                    </button>
                    <!-- <button id="btn_delete" type="button" class="btn btn-default">
                        <span class="glyphicon glyphicon-remove" aria-hidden="true"></span>删除
                    </button> -->
                </div>
        </div>
    
        <table id="tb_dept" >
            <thead>
                <tr>
                    <th data-checkbox="true"></th>
                    <th data-field="account">登录名</th>
                    <th data-field="userName">真实名</th>
                    <th data-field="phone">电话</th>
                    <th data-field="deptName">部门</th>
                    <th data-field="updateTime">创建时间</th>
                    <th data-field="roles" data-formatter="operateRoles">角色</th>
                    <th data-field="operate" data-formatter="operateFormatter">操作</th>
                </tr>
            </thead>
        </table>
    </div>
</body>
<!-- 全局js -->
<script src="../../js/jquery.min.js?v=2.1.4"></script>
<script src="../../js/bootstrap.min.js?v=3.3.6"></script>

<!-- 自定义js -->
<script src="../../js/content.js?v=1.0.0"></script>
<!-- layerDate plugin javascript -->
<script src="../../js/plugins/layer/laydate/laydate.js"></script>

<!-- Bootstrap table -->
<script src="../../js/plugins/bootstrap-table/bootstrap-table.min.js"></script>
<script src="../../js/plugins/bootstrap-table/bootstrap-table-mobile.min.js"></script>
<script src="../../js/plugins/bootstrap-table/locale/bootstrap-table-zh-CN.min.js"></script>
<!--MVVM框架-->
<script type="text/javascript" src="../../js/plugins/knockout/knockout-3.4.2.js"></script>
<script type="text/javascript" src="../../js/plugins/knockout/knockout.mapping-latest.js"></script>
<!--mvvm自定义插件-->
<!-- <script type="text/javascript" src="../../js/ko.bootstrap.table.js"></script> -->
<!--<script src="http://static.runoob.com/assets/jquery-validation-1.14.0/dist/jquery.validate.min.js"></script>-->
<!--<script src="http://static.runoob.com/assets/jquery-validation-1.14.0/dist/localization/messages_zh.js"></script>-->
<script type="text/javascript" src="../../js/common/auth.js"></script>
<script id="addTpl" type="text/html" >
    <div class="form-horizontal"style="overflow: hidden;margin-top: 20px">
	    <div class="form-group">
	        <label for="account" class="col-sm-3 control-label">登录名</label>
	        <div class="col-sm-8">
	          	<input type="text" class="form-control" data-bind='value:account'  id="account" placeholder="请输入登录名">
	        </div>
	        <span class="req" style=" display: inline-block;margin-top: 6px;color: red;font-size: 20px;">*</span>
	    </div>
	    <div class="form-group">
	        <label for="userName" class="col-sm-3 control-label">真实姓名</label>
	        <div class="col-sm-8">
	          	<input type="text" class="form-control" data-bind='value: userName' id="userName" placeholder="请输入真实姓名">
	        </div>
	    </div>
	    <div class="form-group">
	        <label for="namePinyin" class="col-sm-3 control-label">姓名拼音</label>
	        <div class="col-sm-8">
	          <input type="text" class="form-control" data-bind='value: namePinyin' id="namePinyin" placeholder="请输入姓名拼音">
	        </div>
	    </div>  
	    <div class="form-group">
	        <label for="password" class="col-sm-3 control-label">密码</label>
	        <div class="col-sm-8">
	            <input type="password" class="form-control" data-bind='value: password' id="password" placeholder="请输入密码">
	        </div>
	        <span class="req" style=" display: inline-block;margin-top: 6px;color: red;font-size: 20px;">*</span>
	    </div>
	    <div class="form-group">
            <label for="avatar" class="col-sm-3 control-label">头像</label>
            <div class="col-sm-8">
            	<input style='display: none;' data-bind='value:avatar' id="avatar"/>
            	<img id="suolue"  src="../../img/moren.jpg" alt="" width="100px" height="100px">
                <input type="file" style='display: inline-block;'  id="fileInput"/>
            </div>
        </div>
	    <div class="form-group">
	        <label for="userType" class="col-sm-3 control-label">用户类型</label>
	        <div class="col-sm-8">
		        <select data-bind="value:userType" id="userType" class="form-control">
		        	<option value="" style="color:green;">请选择</option>
			        <option value="1" style="color:green;">普通用户</option>
			        <option value="2" style="color:green;">管理员</option>
			        <option value="3" style="color:green;">系统用户</option>
		        </select>
	        </div>
	    </div>
	    <div class="form-group">
	        <label for="email" class="col-sm-3 control-label">Email</label>
	        <div class="col-sm-8">
	          <input type="email" class="form-control" data-bind='value: email' id="email"  placeholder="Email">
	        </div>
	    </div>
	    <div class="form-group">
	        <label class="col-sm-3 control-label">性别</label>
	        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="radio"  class=" setOs" data-bind='checked: sex' name="sex" value="0"/>未知
	        <input type="radio"  class=" setOs" data-bind='checked: sex' name="sex" value="1"/>男
	        <input type="radio"  class=" setOs" data-bind='checked: sex' name="sex" value="2"/>女
	    </div>
	    <div class="form-group">
	        <label for="phone" class="col-sm-3 control-label">电话</label>
	        <div class="col-sm-8">
	            <input type="text" class="form-control" data-bind='value: phone' id="phone"  placeholder="输入电话号码">
	        </div>
	        <span class="req" style=" display: inline-block;margin-top: 6px;color: red;font-size: 20px;">*</span>
	    </div>
	    <div class="form-group">
	        <label for="idCard" class="col-sm-3 control-label">身份证号码</label>
	        <div class="col-sm-8">
	            <input type="text" class="form-control" data-bind='value: idCard' id="idCard"  placeholder="输入身份证号码">
	        </div>
	    </div>
	    <div class="form-group">
	        <label for="birthDay" class="col-sm-3 control-label">出生日期</label>
	        <div class="col-sm-8">
	            <input type="text" class="form-control" data-bind='value: birthDay' id="birthDay"  placeholder="输入出生日期">
	        </div>
	    </div>
	    <div class="form-group">
	        <label for="deptId" class="col-sm-3 control-label">所属部门</label>
	        <div class="col-sm-8">
	            <select data-bind="value:deptId" id="deptId" class="form-control">
	            	<option value="">请选择</option>
	            </select>
	        </div>
	    </div>
	    <div class="form-group">
	        <label for="position" class="col-sm-3 control-label">职位</label>
	        <div class="col-sm-8">
	            <input type="text" class="form-control" data-bind='value: position' id="position"  placeholder="输入职位">
	        </div>
	    </div>
	    <div class="form-group">
	        <label for="address" class="col-sm-3 control-label">详细地址</label>
	        <div class="col-sm-8">
	            <input type="text" class="form-control" data-bind='value: address' id="address"  placeholder="输入详细地址">
	        </div>
	    </div>
		<div class="form-group">
	        <label for="qq" class="col-sm-3 control-label">QQ</label>
	        <div class="col-sm-8">
	            <input type="text" class="form-control" data-bind='value: qq' id="qq"  placeholder="输入QQ号码">
	        </div>
	    </div>
	    <div class="form-group">
	        <label for="remark" class="col-sm-3 control-label">备注</label>
	        <div class="col-sm-8">
	            <input type="text" class="form-control" data-bind='value: remark' id="remark"  placeholder="输入备注">
	        </div>
	    </div>
	    <div class="form-group">
	        <label for="weiBo" class="col-sm-3 control-label">微博</label>
	        <div class="col-sm-8">
	            <input type="text" class="form-control" data-bind='value: weiBo' id="weiBo"  placeholder="输入微博账号">
	        </div>
	    </div>
	    <div class="form-group">
	        <label for="weiXin" class="col-sm-3 control-label">微信</label>
	        <div class="col-sm-8">
	            <input type="text" class="form-control" data-bind='value: weiXin' id="weiXin"  placeholder="输入微信号">
	        </div>
	    </div>
	</div>
</script>

<script id="updateTpl" type="text/html" >
    <div class="form-horizontal"style="overflow: hidden;margin-top: 20px">
        <div class="form-group">
	        <label for="account" class="col-sm-3 control-label">登录名</label>
	        <div class="col-sm-8">
	          	<input type="text" class="form-control" data-bind='value:account'  id="account" placeholder="请输入登录名">
	        </div>
	        <span class="req" style=" display: inline-block;margin-top: 6px;color: red;font-size: 20px;">*</span>
	    </div>
	    <div class="form-group">
	        <label for="userName" class="col-sm-3 control-label">真实姓名</label>
	        <div class="col-sm-8">
	          <input type="text" class="form-control" data-bind='value: userName' id="userName" placeholder="请输入真实姓名">
	        </div>
	    </div>
	    <div class="form-group">
	        <label for="namePinyin" class="col-sm-3 control-label">姓名拼音</label>
	        <div class="col-sm-8">
	          <input type="text" class="form-control" data-bind='value: namePinyin' id="namePinyin" placeholder="请输入姓名拼音">
	        </div>
	    </div>  
	    <div class="form-group">
	        <label for="password" class="col-sm-3 control-label">密码</label>
	        <div class="col-sm-8">
	            <input type="password" class="form-control" data-bind='value: password' id="password" placeholder="请输入密码">
	        </div>
	        <span class="req" style=" display: inline-block;margin-top: 6px;color: red;font-size: 20px;">*</span>
	    </div>
	    <div class="form-group">
            <label for="avatar" class="col-sm-3 control-label">头像</label>
            <div class="col-sm-8">
            	<img id="suolue" data-bind='attr:{src:avatar}'  height="100px" width="100px"/>
            </div>
        </div>
	    <div class="form-group">
            <label for="avatar" class="col-sm-3 control-label">头像上传</label>
            <div class="col-sm-8">
            	<input style='display: none;' data-bind='value:avatar' id="avatar"/>
                <input type="file" style='display: inline-block;'  id="fileInput"/>
            </div>
        </div>
	    <div class="form-group">
	        <label for="userType" class="col-sm-3 control-label">用户类型</label>
	        <div class="col-sm-8">
		        <select data-bind="value:userType" id="userType" class="form-control">
		        	<option value="" style="color:green;">请选择</option>
		           	<option value="1" style="color:green;">普通用户</option>
		           	<option value="2" style="color:green;">管理员</option>
		           	<option value="3" style="color:green;">系统用户</option>
		        </select>
	        </div>
	    </div>
	    <div class="form-group">
	        <label for="email" class="col-sm-3 control-label">Email</label>
	        <div class="col-sm-8">
	          <input type="email" class="form-control" data-bind='value: email' id="email"  placeholder="Email">
	        </div>
	    </div>
	    <div class="form-group">
	        <label class="col-sm-3 control-label">性别</label>
	        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="radio"  class=" setOs" data-bind='checked: sex' name="sex" value="0"/>未知
	        <input type="radio"  class=" setOs" data-bind='checked: sex' name="sex" value="1"/>男
	        <input type="radio"  class=" setOs" data-bind='checked: sex' name="sex" value="2"/>女
	    </div>
	    <div class="form-group">
	        <label for="phone" class="col-sm-3 control-label">电话</label>
	        <div class="col-sm-8">
	            <input type="text" class="form-control" data-bind='value: phone' id="phone"  placeholder="输入电话号码">
	        </div>
	        <span class="req" style=" display: inline-block;margin-top: 6px;color: red;font-size: 20px;">*</span>
	    </div>
	    <div class="form-group">
	        <label for="idCard" class="col-sm-3 control-label">身份证号码</label>
	        <div class="col-sm-8">
	            <input type="text" class="form-control" data-bind='value: idCard' id="idCard"  placeholder="输入身份证号码">
	        </div>
	    </div>
	    <div class="form-group">
	        <label for="birthDay" class="col-sm-3 control-label">出生日期</label>
	        <div class="col-sm-8">
	            <input type="text" class="form-control" data-bind='value: birthDay' id="birthDay"  placeholder="输入出生日期">
	        </div>
	    </div>
	    <div class="form-group">
	        <label for="deptId" class="col-sm-3 control-label">所属部门</label>
	        <div class="col-sm-8">
	            <select data-bind="value:deptId" id="deptId" class="form-control">
	            	<option value="">请选择</option>
	            </select>
	        </div>
	    </div>
	    <div class="form-group">
	        <label for="position" class="col-sm-3 control-label">职位</label>
	        <div class="col-sm-8">
	            <input type="text" class="form-control" data-bind='value: position' id="position"  placeholder="输入职位">
	        </div>
	    </div>
	    <div class="form-group">
	        <label for="address" class="col-sm-3 control-label">详细地址</label>
	        <div class="col-sm-8">
	            <input type="text" class="form-control" data-bind='value: address' id="address"  placeholder="输入详细地址">
	        </div>
	    </div>
		<div class="form-group">
	        <label for="qq" class="col-sm-3 control-label">QQ</label>
	        <div class="col-sm-8">
	            <input type="text" class="form-control" data-bind='value: qq' id="qq"  placeholder="输入QQ号码">
	        </div>
	    </div>
	    <div class="form-group">
	        <label for="remark" class="col-sm-3 control-label">备注</label>
	        <div class="col-sm-8">
	            <input type="text" class="form-control" data-bind='value: remark' id="remark"  placeholder="输入备注">
	        </div>
	    </div>
	    <div class="form-group">
	        <label for="weiBo" class="col-sm-3 control-label">微博</label>
	        <div class="col-sm-8">
	            <input type="text" class="form-control" data-bind='value: weiBo' id="weiBo"  placeholder="输入微博账号">
	        </div>
	    </div>
	    <div class="form-group">
	        <label for="weiXin" class="col-sm-3 control-label">微信</label>
	        <div class="col-sm-8">
	            <input type="text" class="form-control" data-bind='value: weiXin' id="weiXin"  placeholder="输入微信号">
	        </div>
	    </div>
    </div>
</script>

<script id="updateTp2" type="text/html" >
    <div class="form-horizontal" style="overflow: hidden;margin-top: 20px">
        <div class="form-group">
            <label for="newPassword" class="col-sm-3 control-label">新密码：</label>
            <div class="col-sm-8">
                <input type="text" class="form-control" id="newPassword" placeholder="请输入密码">
            </div>
        </div>
    </div>
</script>

<script id="updateRole" type="text/html" >
    <div class="form-horizontal" style="overflow: hidden;margin-top: 20px">
        <div class="form-group">
            <label for="roles" class="col-sm-3 control-label">角色：</label>
            <div class="col-sm-8" id="roles" style="margin-top: 4px;"></div>
        </div>
    </div>    
</script>

<script id="AddRole" type="text/html" >
    <div class="form-horizontal" style="overflow: hidden;margin-top: 20px">
        <div class="form-group">
            <label for="roles" class="col-sm-3 control-label">角色：</label>
            <div class="col-sm-8" id="roles" style="margin-top: 4px;"></div>
        </div>
    </div>    
</script>
<script type="text/javascript">
    var __addUrl = "/user";//post
    var __listUrl = "/user/read/list";  //put
    var __listRoleUrl = "/role/read/list"
    var __listDeptUrl = "/dept/read/list"
    var __delUrl = "../../user"; //delete 方式
    var __updateCurUrl = "/user/update/person";
    var __detailUrl="/user/read/detail";
    var __UpdatePassword = "../../user";//post;
    var __UpdateUserRole = "/sysUserRole/allUpdate";//post;
    var __upload = "/upload/temp/image/to/oss" ;//图片上传
	var maxHeight = top.document.body.clientHeight * 0.8 ; //文档高度的80%
    //初始化
    $(function () {
        //1、初始化表格
        tableInit.Init();

        //2、注册增删改事件
        operate.operateInit();
        
        //时间初始化
		dateInit.Init();
    });
    
    var koModel={
        searchModel:{
             account:ko.observable(),
        }
	};
    //初始化表格
    var tableInit = {
        Init: function () {
            function queryParams(param){
            	var unmapped = ko.mapping.toJS(koModel.searchModel);
            	var pa = { pageSize: param.limit, pageNum : param.offset/param.limit+1 }
                if($("#startTime").val()){
                    pa.startTime = $("#startTime").val();
                }
                if($("#endTime").val()){
                    pa.endTime = $("#endTime").val();
                }
                //alert(JSON.stringify($.extend(pa,unmapped)));
                return JSON.stringify($.extend(pa,unmapped));
            }

            $("#tb_dept").bootstrapTable({
                url: __listUrl,
                method: 'put',                      //请求方式（*）
                toolbar: '#toolbar',                //工具按钮用哪个容器
                queryParams: queryParams,           //传递参数（*）
                pagination: true,                   //是否显示分页（*）
                sidePagination: "server",           //分页方式：client客户端分页，server服务端分页（*）
                paginationHAlign:"right",
                uniqueId:"id",
                pageNumber: 1,                      //初始化加载第一页，默认第一页
                pageSize: 10,                       //每页的记录行数（*）
                pageList: [10, 25, 50, 100],       //可供选择的每页的行数（*）
                search: false,                       //是否显示表格搜索，此搜索是客户端搜索，不会进服务端，所以，个人感觉意义不大
                strictSearch: true,
                showColumns: true,                  //是否显示所有的列
                cache:false,
                showRefresh: true,                  //是否显示刷新按钮
                minimumCountColumns: 2,             //最少允许的列数
                clickToSelect: true,                //是否启用点击选中行
                showToggle: false,
                responseHandler:function(res){
                    if(res.httpCode==401){
                       top.window.location.href=top.window.location.origin+"/login.html";
                    }
                    return {
                        "total":res.total,
                        "rows":res.data
                    }
                }
            });
        }
    };
    
    /**
    每行的操作按钮
    */
    function operateFormatter(value, row, index){
       	var html =  '<button  type="button" class="btn btn-default" onclick="operate.operateDelete(\''+row.id+'\')">删除</button>'+
               '&nbsp;&nbsp;<button  type="button" class="btn btn-default" onclick="operate.operateChange(\''+row.id+'\')">更换密码</button>';
        if(row.roles){
        	html += '<button  type="button" class="btn btn-default" onclick="operate.operateUpdateRole(\''+row.id+'\')">修改角色</button>';
        }else{
        	html += '<button  type="button" class="btn btn-default" onclick="operate.operateAddRole(\''+row.id+'\')">分配角色</button>';
        }
        return html;
    }
    
    function operateRoles(value, row, index){
       	if(value){
       		var arr = value;
       		var html = "<p>";
        	for(var i in value){
        		html += "<span class='badge badge-primary'>"+arr[i].roleName+"</span><br/><br/>";
        	}
        	html +="</p>";
        	return html;
       	}else{
       		return "";
       	}
       	 
    }

    function getSelections(){
        return $("#tb_dept").bootstrapTable('getSelections');
    }
    function getTable(){
        return $("#tb_dept");
    }
    function refreshTable(){
        $("#tb_dept").bootstrapTable("refresh");
    }

    //操作
    var operate = {
        //初始化按钮事件
        operateInit: function () {
            this.operateAdd();
            this.operateUpdate();
            this.operateSearch();
            //this.operateDelete();
            this.entityModel ={
                account: ko.observable(),
                userName:ko.observable(),
                namePinyin:ko.observable(),
                password: ko.observable(),
                address: ko.observable(),
                avatar: ko.observable(),
                birthDay: ko.observable(),
                createTime: ko.observable(),
                position: ko.observable(),
                userType: ko.observable(),
                deptId: ko.observable(),
                email: ko.observable(),
                idCard: ko.observable(),
                id: ko.observable(),
                phone: ko.observable(),
                qq: ko.observable(),
                remark: ko.observable(),
                sex: ko.observable(),
                weiBo: ko.observable(),
                weiXin: ko.observable()
            };
        },
        //新增
        operateAdd: function(){
            $('#btn_add').on("click", function () {
                var newModel =   operate.entityModel;
                top.layer.open({
                    title:"用户新增",
                    type: 1,
                    area: "500px",
                    maxHeight:maxHeight,
                    content:$("#addTpl").html(),
                    btn: ["保存", "取消"],
                    yes: function(index, layerDom){
                    	//文件上传
                    	//头像上传
                    	var formData = new FormData();
				        formData.append("myfile", $("#fileInput", $(layerDom)).get(0).files[0]);
				        $.ajax({
				            url: __upload,
				            type: "POST",
				            data: formData,
				            /**
				            *必须false才会自动加上正确的Content-Type
				            */
				            contentType: false,
				            async:false,
				            /**
				            * 必须false才会避开jQuery对 formdata 的默认处理
				            * XMLHttpRequest会对 formdata 进行正确的处理
				            */
				            processData: false,
				            success: function (data) {
				            	if (data.httpCode == "200") {
				                	newModel.avatar(data.urls[0]);
				                    //alert("上传成功！");
				                }else{
				                	console.log(data.msg);
				                }
				            },
				            error: function () {
				                alert("上传失败！！请检查本地网络!");
				            }
				        });
                    	
                        var unmapped = ko.mapping.toJS(newModel);
                        var unmapstr = JSON.stringify(unmapped);
//                        alert(unmapstr);
                        if(!operate.operateCheck(unmapped)){
                            return;
                        }
                        delete unmapstr.id;
                        $$ajax({
                            url: __addUrl,
                            type: 'post',//提交的方式
                            dataType:'json',
                            contentType:"application/json; charset=utf-8",
                            data:JSON.stringify(unmapped),
                            success: function(data) {
                                console.log(data.msg)
                                if (data.httpCode==200) {
                                    refreshTable();
                                    top.layer.alert('更新成功', {icon:6});
                                    top.layer.close(index);
                                } else{
                                    alert(data.msg)
                                }
                            }

                        });
                        
                    },
                    btn2:function(index,layarDom){//关闭
                        ko.cleanNode(layarDom.get(0));
                    },
                    success:function(layarDom,index){//弹层加载成功
                    	
                    	$("#fileInput",$(layarDom)).change(function(){
                    		var file = this.files[0];
						   	if (window.FileReader) {    
					            var reader = new FileReader();    
					            reader.readAsDataURL(file);    
					            //监听文件读取结束后事件    
					          	reader.onloadend = function (e) {
					            	$("#suolue",$(layarDom)).attr("src",e.target.result);    //e.target.result就是最后的路径地址
					            };    
						    } 
                    	});
                    	
                    	var birthDay = $("#birthDay", $(layarDom)).get(0);
                    	top.laydate.render(dateInit.customInitLayDate(birthDay));
                    	
                    	//获取所有的部门
                    	$$ajax({
                            url: __listDeptUrl,
                            type: 'put',//提交的方式
                            dataType:'json',
                            contentType:"application/json; charset=utf-8",
                            async:false,
                            data:JSON.stringify({}),
                            success: function(response) {
                                console.log(response.msg)
                                if (response.httpCode==200) {
                                    var depts = $("#deptId",$(layarDom));
                                    var arr = response.data;
                                    for(var i in arr){
                                    	depts.append("<option value='"+arr[i].id+"'>"+arr[i].deptName+"</option>")
                                    }
                                } else{
                                    alert(response.msg)
                                }
                            }

                        });
                    	
                        ko.applyBindings(newModel, layarDom.get(0));
                        //var unmapped = ko.mapping.toJS(operate.entityModel);
                        

                    }
                });
            });
        },
        //编辑修改
        operateUpdate: function () {
            $('#btn_edit').on("click", function () {
               	var arr =  getSelections();
               	if(arr.length != 1){
                    alert("请选择一条数据!");
                    return;
               	}
             
               	var seletionData = arr[0];
                var newModel =   ko.mapping.fromJS(seletionData);
                top.layer.open({
                    title:"用户信息修改",
                    type: 1,
                    area: "500px",
                    maxHeight:maxHeight,
                    content:$("#updateTpl").html(),
                    btn: ["保存", "取消"],
                    yes: function(index, layerDom){
                    	//文件上传
                    	//头像上传
                    	var formData = new FormData();
				        formData.append("myfile", $("#fileInput", $(layerDom)).get(0).files[0]);
				        $.ajax({
				            url: __upload,
				            type: "POST",
				            data: formData,
				            /**
				            *必须false才会自动加上正确的Content-Type
				            */
				            contentType: false,
				            async:false,
				            /**
				            * 必须false才会避开jQuery对 formdata 的默认处理
				            * XMLHttpRequest会对 formdata 进行正确的处理
				            */
				            processData: false,
				            success: function (data) {
				            	if (data.httpCode == "200") {
				                	newModel.avatar(data.urls[0]);
				                    //alert("上传成功！");
				                }else{
				                	console.log(data.msg);
				                }
				            },
				            error: function () {
				                alert("上传失败！！请检查本地网络!");
				            }
				        });
                    	
                        var jsModle = ko.mapping.toJS(newModel);
                        if(!operate.operateCheck(jsModle)){
                            return;
                        }
                        $$ajax({
                            url: __addUrl,
                            type: 'post',//提交的方式
                            dataType:'json',
                            contentType:"application/json; charset=utf-8",
                            data:JSON.stringify(jsModle),
                            success: function(data) {
                                console.log(data.msg)
                                if (data.httpCode==200) {
                                    top.layer.alert('更新成功', {icon:6});
                                    refreshTable();
                                    top.layer.close(index);
                                } else{
                                    alert(data.msg);
                                }
                            }
                        });

                    },
                    btn2:function(index,layarDom){//关闭
                        ko.cleanNode(layarDom.get(0));
                    },
                    success:function(layarDom,index){//弹层加载成功
                    	
                    	$("#fileInput",$(layarDom)).change(function(){
                    		var file = this.files[0];
						   	if (window.FileReader) {    
					            var reader = new FileReader();    
					            reader.readAsDataURL(file);    
					            //监听文件读取结束后事件    
					          	reader.onloadend = function (e) {
					            	$("#suolue",$(layarDom)).attr("src",e.target.result);    //e.target.result就是最后的路径地址
					            };    
						    } 
                    	});
                    	
                    	var birthDay = $("#birthDay", $(layarDom)).get(0);
                    	top.laydate.render(dateInit.customInitLayDate(birthDay));
                    	
                    	//获取所有的部门
                    	$$ajax({
                            url: __listDeptUrl,
                            type: 'put',//提交的方式
                            dataType:'json',
                            contentType:"application/json; charset=utf-8",
                            async:false,
                            data:JSON.stringify({}),
                            success: function(response) {
                                console.log(response.msg)
                                if (response.httpCode==200) {
                                    var depts = $("#deptId",$(layarDom));
                                    var arr = response.data;
                                    for(var i in arr){
                                    	depts.append("<option value='"+arr[i].id+"'>"+arr[i].deptName+"</option>")
                                    }
                                } else{
                                    alert(response.msg)
                                }
                            }

                        });
                    	
                        ko.applyBindings(newModel, layarDom.get(0));
                        //var unmapped = ko.mapping.toJS(operate.entityModel);


                    }
                });

            });
        },
        //单条删除
        operateDelete: function (id) {
        	if(confirm("确认删除？")){
        		$$ajax({
                    url: __delUrl,
                    type: "delete",
                    contentType: 'application/json',
                    data: JSON.stringify({id:id}),
                    success: function (data, status) {
                        if(data.httpCode==200){
                            top.layer.alert('删除成功', {icon:6});
                            refreshTable();
                        }else{
                             alert(data.msg); 
                        }
                       
                        //tableInit.myViewModel.refresh();
                    }
	            });
        	}
        },
        //单条改密
        operateChange: function (id) {
            var row = getTable().bootstrapTable("getRowByUniqueId",id);
            top.layer.open({
                title:"密码修改",
                type: 1,
                area: ["500px", "250px"],
                content:$("#updateTp2").html(),
                btn: ["保存", "取消"],
                yes: function(index, layerDom){
                    $$ajax({
                        url: __UpdatePassword,
                        type: 'post',//提交的方式
                        dataType:'json',
                        contentType:"application/json; charset=utf-8",
                        data:JSON.stringify({id:id,account:row.account,password:$("#newPassword", $(layerDom)).val()}),
                        success: function(data) {
                            console.log(data.msg)
                            if (data.httpCode==200) {
                                top.layer.alert('更新成功', {icon:6});
                                top.layer.close(index);
                                refreshTable();
                            } else{
                                alert(data.msg);
                                location.reload();
                            }
                        }
                    });

                },
                btn2:function(index,layarDom){//关闭
                    ko.cleanNode(layarDom.get(0));
                },
                success:function(layerDom,index){//弹层加载成功

                }
            });
        },
        
        
        //修改角色
        operateUpdateRole: function (id) {
        	var row = getTable().bootstrapTable("getRowByUniqueId",id);
        	var roleIds=[];
        	for(var i in row.roles){
        		roleIds.push(row.roles[i].id);
        	}
        	row.isCheck = roleIds;
        	var newModel = ko.mapping.fromJS(row);
            top.layer.open({
                title:"修改角色",
                type: 1,
                area: ["500px", "250px"],
                content:$("#updateRole").html(),
                btn: ["保存", "取消"],
                yes: function(index, layerDom){
                	var arr = [];
                	$("input:checked",$(layerDom)).each(function(){
                		arr.push($(this).val())
                	});
                	
                	//保存用户角色对应关系
                    $$ajax({
                        url: __UpdateUserRole,
                        type: 'post',//提交的方式
                        dataType:'json',
                        contentType:"application/json; charset=utf-8",
                        data:JSON.stringify({userId:id,roleArr:arr}),
                        success: function(response) {
                            console.log(response.msg)
                            if (response.httpCode==200) {
                            	top.layer.alert('更新成功', {icon: 6});
                            	refreshTable();
                            	top.layer.close(index);
                            } else{
                                alert(response.msg);
                                location.reload();
                            }
                        }
                    });
                },
                btn2:function(index,layarDom){//关闭
                    ko.cleanNode(layarDom.get(0));
                },
                success:function(layerDom,index){//弹层加载成功
                	//获取所有角色
					$$ajax({
                        url: __listRoleUrl,
                        type: 'put',//提交的方式
                        dataType:'json',
                        async:false,
                        contentType:"application/json; charset=utf-8",
                        data:JSON.stringify({}),
                        success: function(response) {
                            console.log(response.msg)
                            if (response.httpCode==200) {
                            	var arr = response.data;
                            	var roles = $("#roles",$(layerDom));
                            	for(var i in arr){
                            		roles.append("<input type='checkbox' data-bind='checked : isCheck' name='role' value='"+arr[i].id+"'>"+arr[i].roleName+"&nbsp&nbsp");
                            	}
                            } else{
                                alert(response.msg);
                            }
                        }
                    });
                    
					ko.applyBindings(newModel, layerDom.get(0));
                }
            });
        },
        
        //分配角色
        operateAddRole: function (id) {
            top.layer.open({
                title:"分配角色",
                type: 1,
                area: ["500px", "250px"],
                content:$("#AddRole").html(),
                btn: ["保存", "取消"],
                yes: function(index, layerDom){
                	var arr = [];
                	$("input:checked",$(layerDom)).each(function(){
                		arr.push($(this).val())
                	});
                	if(arr.length>0){
                		//保存用户角色对应关系
	                    $$ajax({
	                        url: __UpdateUserRole,
	                        type: 'post',//提交的方式
	                        dataType:'json',
	                        contentType:"application/json; charset=utf-8",
	                        data:JSON.stringify({userId:id,roleArr:arr}),
	                        success: function(response) {
	                            console.log(response.msg)
	                            if (response.httpCode==200) {
	                            	top.layer.alert('分配成功', {icon: 6});
	                            	refreshTable();
	                            	top.layer.close(index);
	                            } else{
	                                alert(response.msg);
	                            }
	                        }
	                    });
                	}else{
                		top.layer.alert('你没有选择任何角色', {icon: 6});
                	}
                	
                },
                btn2:function(index,layarDom){//关闭
                    ko.cleanNode(layarDom.get(0));
                },
                success:function(layerDom,index){//弹层加载成功
                	//获取所有角色
					$$ajax({
                        url: __listRoleUrl,
                        type: 'put',//提交的方式
                        dataType:'json',
                        async:false,
                        contentType:"application/json; charset=utf-8",
                        data:JSON.stringify({}),
                        success: function(response) {
                            console.log(response.msg)
                            if (response.httpCode==200) {
                            	var arr = response.data;
                            	var roles = $("#roles",$(layerDom));
                            	for(var i in arr){
                            		roles.append("<input type='checkbox' data-bind='checked : isCheck' name='role' value='"+arr[i].id+"'>"+arr[i].roleName+"&nbsp&nbsp");
                            	}
                            } else{
                                alert(response.msg);
                            }
                        }
                    });
                }
            });
        },
        
        //搜索清空绑定
        operateSearch:function(){
            //ko模型绑定
            ko.applyBindings(koModel.searchModel, $("#toolbar").get(0));
            $("#btn_search").click(function(event) {
                var searchObj = ko.mapping.toJS(koModel.searchModel);
                //alert(JSON.stringify(searchObj));
                $("#tb_dept").bootstrapTable("refreshOptions",{pageNumber:1});
                refreshTable();
            });
        },
        
        //数据校验
        operateCheck:function(entity){
          var reacc =  /^[a-zA-Z][a-zA-Z0-9]*$/g;
            if (entity.account=="") {
                alert("用户名不能为空，请填写用户名!");
                return false;
            }
            if (!reacc.test(entity.account)) {
                alert("用户名只能是字母和数字的组合!");
                return false;
            }
            if (entity.password=="") {
                alert("密码不能为空，请输入密码!");
                return false;
            }
            var re = /^(\w-*\.*)+@(\w-?)+(\.\w{2,})+$/;
            if (!re.test(entity.email)) {
                alert("邮箱不合法!");
                return false;
            }
            if (entity.phone=="") {
                alert("手机号不能为空，请输入手机号!");
                return false;
            }
         var  rep = /(1[3-9]\d{9}$)/;
            if(!rep.test(entity.phone))
            {
                alert("手机号码格式不对！");
                return false;
            }
            return true;
        }
    }
	var dateInit = {
        Init: function () {
            var that = this;
            laydate.render(this.customInitLayDate($("#startTime").get(0)));
            laydate.render(this.customInitLayDate($("#endTime").get(0)));
        },
        customInitLayDate: function (elem) {
        	//elem 传入的 原生dom 对象
            return {
                elem: elem,//
                format: 'yyyy-MM-dd HH:mm:ss',
                min: '1971-01-01 00:00:00', //设定最小日期为当前日期
                max: '2099-06-16 23:59:59', //最大日期
                istime: true,
                istoday: false,
                done:function  (value, date, endDate) {
               		$(elem).change();
                }
            }
        }
    }
</script>

</html>